package com.ami.kvm.jviewer.kvmpkts;

import com.ami.kvm.jviewer.Debug;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class KMCrypt {
	public static final int ENCRYPT = 1;
	public static final int DECRYPT = 2;
	public static final int PLACE_HOLDER_SIZE = 16;
	private Cipher m_bf = null;

	public int initialize(String paramString, int paramInt) {
		byte[] arrayOfByte1 = new byte[16];
		byte[] arrayOfByte2 = paramString.getBytes();

		if (arrayOfByte2.length < 16) {
			for (int i = 0; i < arrayOfByte2.length; i++)
				arrayOfByte1[i] = arrayOfByte2[i];
		} else {
			arrayOfByte1 = paramString.getBytes();
		}
		if (arrayOfByte1 == null) {
			return -1;
		}

		SecretKeySpec localSecretKeySpec = new SecretKeySpec(arrayOfByte1, "Blowfish");
		try {
			this.m_bf = Cipher.getInstance("Blowfish/ECB/NoPadding");
			this.m_bf.init(paramInt, localSecretKeySpec);
		} catch (Exception localException) {
			Debug.out.println("Crypt initialization failed\n");
			Debug.out.println(localException);
			return -1;
		}
		return 0;
	}

	public byte[] encrypt(byte[] paramArrayOfByte) {
		byte[] arrayOfByte1 = pad(paramArrayOfByte);
		byte[] arrayOfByte2;
		try {
			arrayOfByte2 = this.m_bf.doFinal(arrayOfByte1);
		} catch (Exception localException) {
			Debug.out.println(localException);
			Debug.out.println("Encryption failed\n");
			return null;
		}
		return arrayOfByte2;
	}

	public byte[] decrypt(byte[] paramArrayOfByte) {
		byte[] arrayOfByte;

		try {
			arrayOfByte = this.m_bf.doFinal(paramArrayOfByte);
		} catch (Exception localException) {
			Debug.out.println("Decryption failed\n");
			Debug.out.println(localException);
			return null;
		}
		return arrayOfByte;
	}

	public void close() {
		this.m_bf = null;
	}

	public boolean isInitialized() {
		if (this.m_bf == null) {
			return false;
		}
		return true;
	}

	private byte[] pad(byte[] paramArrayOfByte) {
		if (paramArrayOfByte.length % 8 == 0) {
			return paramArrayOfByte;
		}
		byte[] arrayOfByte = new byte[paramArrayOfByte.length + (8 - paramArrayOfByte.length % 8)];
		Arrays.fill(arrayOfByte, (byte) 0);
		System.arraycopy(paramArrayOfByte, 0, arrayOfByte, 0, paramArrayOfByte.length);
		return arrayOfByte;
	}
}